package com.ruoyi.web.controller.nongjt;


import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.jwt.JwtUtil;

import com.ruoyi.nongjt.domain.pojo.NjtSupervisor;
import com.ruoyi.nongjt.domain.pojo.NjtUserRegister;
import com.ruoyi.nongjt.service.NjtSupervisorService;
import com.ruoyi.nongjt.service.NjtUserRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/nongjt/userAuth")
public class NjtUserLoginController extends BaseController {
    @Autowired
    private NjtUserRegisterService njtUserRegisterService;
    @Autowired
    private NjtSupervisorService njtSupervisorService;
    @Autowired
    private RedisCache redisCache;

    @PostMapping("/register")
    public AjaxResult register(@RequestBody NjtUserRegister userRegister) {
        // 获取参数
        String mobilePhone = userRegister.getMobilePhone();
        String password = userRegister.getPassword();
        String captcha = userRegister.getCaptcha(); // 新增字段：前端传来的验证码
        String uuid = userRegister.getUuid();       // 新增字段：前端传来的 uuid

        // 校验基础信息
        if (StringUtils.isAnyBlank(mobilePhone, password, captcha, uuid)) {
            return AjaxResult.error("手机号、密码、验证码或UUID不能为空");
        }

        if (!mobilePhone.matches("^1[3-9]\\d{9}$")) {
            return AjaxResult.error("手机号格式不正确");
        }

        //  校验图形验证码
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String correctCaptcha = redisCache.getCacheObject(verifyKey);

        if (correctCaptcha == null) {
            return AjaxResult.error("验证码已过期，请重新获取");
        }
        if (!correctCaptcha.equalsIgnoreCase(captcha)) {
            return AjaxResult.error("验证码错误");
        }

        // 验证通过后删除 Redis 中的验证码（防止重放）
        redisCache.deleteObject(verifyKey);

        // 检查是否已注册
        NjtUserRegister existUser = njtUserRegisterService.getUserByPhone(mobilePhone);
        if (existUser != null) {
            return AjaxResult.error("该手机号已注册");
        }

        // 插入新用户
        int rows = njtUserRegisterService.insertNjtUserRegister(userRegister);
        if (rows > 0) {
            return AjaxResult.success("注册成功");
        } else {
            return AjaxResult.error("注册失败");
        }
    }
    // 添加依赖注入

//    @PostMapping("/login")
//    public AjaxResult login(@RequestBody NjtUserRegister userLogin) {
//        String mobilePhone = userLogin.getMobilePhone();
//        String password = userLogin.getPassword();
//
//        if (mobilePhone == null || password == null) {
//            return AjaxResult.error("手机号或密码不能为空");
//        }
//
//        if (!mobilePhone.matches("^1[3-9]\\d{9}$")) {
//            return AjaxResult.error("手机号格式不正确");
//        }
//
//        NjtUserRegister user = njtUserRegisterService.getUserByPhone(mobilePhone);
//        if (user == null) {
//            return AjaxResult.error("用户不存在");
//        }
//
//        // ✅ 直接字符串比对，因为 password 是 MD5
//        if (!password.equals(user.getPassword())) {
//            return AjaxResult.error("密码错误");
//        }
//
//        String token = JwtUtil.generateToken(mobilePhone);
//        return AjaxResult.success()
//                .put("token", token)
//                .put("user", user);
//    }
    @PostMapping("/login")
    public AjaxResult login(@RequestBody NjtUserRegister userLogin) {
        String mobilePhone = userLogin.getMobilePhone();
        String password = userLogin.getPassword();

        if (mobilePhone == null || password == null) {
            return AjaxResult.error("手机号或密码不能为空");
        }

        if (!mobilePhone.matches("^1[3-9]\\d{9}$")) {
            return AjaxResult.error("手机号格式不正确");
        }

        // 1. 先查监管者表
        NjtSupervisor supervisor = njtSupervisorService.getSupervisorByPhone(mobilePhone);
        if (supervisor != null && password.equals(supervisor.getPassword())) {
            String token = JwtUtil.generateToken(mobilePhone);

            // ✅ 只返回 token 和角色，不操作 LoginUser
            return AjaxResult.success("登录成功")
                    .put("token", token)
                    .put("user", supervisor)
                    .put("role", "supervisor");
        }

        // 2. 再查普通用户表
        NjtUserRegister user = njtUserRegisterService.getUserByPhone(mobilePhone);
        if (user != null && password.equals(user.getPassword())) {
            String token = JwtUtil.generateToken(mobilePhone);

            return AjaxResult.success("登录成功")
                    .put("token", token)
                    .put("user", user)
                    .put("role", "normal");
        }

        return AjaxResult.error("手机号或密码错误");
    }

    @PostMapping("/forgetPassword")
    public AjaxResult forgetPassword(@RequestBody NjtUserRegister userRegister) {
        // 获取参数
        String mobilePhone = userRegister.getMobilePhone();
        String newPassword = userRegister.getPassword(); // 新密码（前端已 MD5）
        String captcha = userRegister.getCaptcha();
        String uuid = userRegister.getUuid();

        // 校验基础信息
        if (StringUtils.isAnyBlank(mobilePhone, newPassword, captcha, uuid)) {
            return AjaxResult.error("手机号、密码、验证码或UUID不能为空");
        }

        if (!mobilePhone.matches("^1[3-9]\\d{9}$")) {
            return AjaxResult.error("手机号格式不正确");
        }

        // 校验图形验证码
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String correctCaptcha = redisCache.getCacheObject(verifyKey);

        if (correctCaptcha == null) {
            return AjaxResult.error("验证码已过期，请重新获取");
        }
        if (!correctCaptcha.equalsIgnoreCase(captcha)) {
            return AjaxResult.error("验证码错误");
        }

        // 验证通过后删除 Redis 中的验证码
        redisCache.deleteObject(verifyKey);

        // ✅ 查询两张表，看手机号是否存在
        boolean userExists = false;
        boolean isSupervisor = false;

        NjtSupervisor supervisor = njtSupervisorService.getSupervisorByPhone(mobilePhone);
        if (supervisor != null) {
            userExists = true;
            isSupervisor = true;
        } else {
            NjtUserRegister normalUser = njtUserRegisterService.getUserByPhone(mobilePhone);
            if (normalUser != null) {
                userExists = true;
                isSupervisor = false;
            }
        }

        if (!userExists) {
            return AjaxResult.error("该手机号未注册，无法重置密码");
        }

        // 存在则更新密码
        int rows = 0;
        if (isSupervisor) {
            rows = njtSupervisorService.resetPasswordByPhone(mobilePhone, newPassword);
        } else {
            rows = njtUserRegisterService.resetPasswordByPhone(mobilePhone, newPassword);
        }

        if (rows > 0) {
            return AjaxResult.success("密码重置成功，请使用新密码登录");
        } else {
            return AjaxResult.error("密码重置失败，请稍后重试");
        }
    }


}
